﻿using UnityEngine;
using System.Collections;

/////////////////////////////////////////////////////////////////////
// 颜色渐变器
// 将整条视为多段,每次获取段的渐变.
/////////////////////////////////////////////////////////////////////
[System.Serializable]
public class UIColorFader {
	public Color[] colors = new Color[]{Color.red,Color.green,Color.blue};
	public float[] percents = new float[]{0.1f,0.6f,1f};
	public int startIndex;
	
	/**
		获取 渐变的颜色
	*/
	public Color GetFadeColor(float value){
		startIndex = GetPercentIndex(value);
		Color c = colors[0];
		
		if(startIndex >= 0){
			if(startIndex + 1 < colors.Length){
				float factor = GetPercent(value,startIndex);
				c = Color.Lerp(colors[startIndex],colors[startIndex+1],factor);
			}else if(startIndex < colors.Length){
				c = colors[startIndex];
			}else
				c = colors[colors.Length - 1];
		}
		return c;
	}
	
	/**
		获取 value在渐变段中的比例.
	*/
	private float GetPercent(float value,int startIndex){
		return (value - percents[startIndex])/(percents[startIndex+1]-percents[startIndex]);
	}
	
	/**
		获取 value处于的渐变段.
	*/
	private int GetPercentIndex(float value){
		for(int i=0;i<percents.Length;i++){
			float p = percents[i];
			if(p - value >= 0){
				return i-1;
			}
		}
		return 0;
	}
}
